package logic

import (
	"context"
	"io"
	"net/http"

	"goNutpi/internal/svc"
	"goNutpi/internal/types"

	htmltomarkdown "github.com/JohannesKaufmann/html-to-markdown/v2"
	"github.com/tidwall/gjson"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpc"
)

type TopicDetailLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewTopicDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *TopicDetailLogic {
	return &TopicDetailLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *TopicDetailLogic) TopicDetail(req *types.TopicDetailReq) (resp *types.TopicDetailResp, err error) {
	// todo: add your logic here and delete this line
	url := "https://api.nutpi.net/thread?topicId=" + req.Id
	res, err_ := httpc.Do(l.ctx, http.MethodGet, url, nil)
	if err_ != nil {
		l.Error(err_)
		return nil, err_
	}
	defer res.Body.Close()
	body, err := io.ReadAll(res.Body)
	if err != nil {
		l.Errorf("Failed to read response body:", err)
		return nil, err
	}
	//格式化输出json
	//var str bytes.Buffer
	//_ = json.Indent(&str, []byte(body), "", "    ")
	//l.Debugf("formated: ", str.String())
	//l.Debug(keyValue)
	var respData types.TopicItem

	rec := gjson.ParseBytes(body)

	respData.Id = rec.Get("id").String()
	respData.Title = rec.Get("title").String()
	respData.TagId = rec.Get("tagId").String()
	respData.TagName = rec.Get("tagName").String()
	respData.Summary = rec.Get("summary").String()
	respData.Content = rec.Get("content").String()
	respData.PostTime = rec.Get("postTime").String()
	respData.Avatar = rec.Get("avatarPath").String() + rec.Get("avatarName").String()
	respData.ViewCnt = rec.Get("viewTotal").String()
	respData.Nickname = rec.Get("nickname").String()
	l.Infof("id: %s, title: %s\n", respData.Id, respData.Title)
	respData.Cover = ""
	markdown, err := htmltomarkdown.ConvertString(respData.Content)
	if err != nil {
		respData.Content = ""
		l.Error(err)
	} else {
		respData.Content = markdown
	}
	//t := reflect.TypeOf(keyVal["count"])
	//l.Debugf("Type: %v\n", t)

	if res.StatusCode >= 200 && res.StatusCode < 400 {
		resp = &types.TopicDetailResp{
			Code:    0,
			Message: res.Status,
			Data:    respData,
		}
	} else {
		resp = &types.TopicDetailResp{
			Code:    res.StatusCode,
			Message: res.Status,
			Data:    types.TopicItem{},
		}
	}
	return resp, nil
}
